//
//  DScreeningViewController.m
//  InformationFoot
//
//  Created by dai on 2018/7/16.
//  Copyright © 2018年 MacBook. All rights reserved.
//

#import "DScreeningViewController.h"

#import "MJRefresh.h"
#import "MXScreeningCollectionViewCell.h"
#import "MXScreeningHeaderCollectionReusableView.h"
#import "MXDAllEventsModel.h"

@interface DScreeningViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic ,strong) UICollectionViewFlowLayout * customLayout ;
@property (nonatomic ,strong) UICollectionView * collectionView ;

//存放选中赛事的ID
@property (nonatomic , strong) NSString * allScreeningIDsString ;
@property (nonatomic , strong) NSMutableArray * dataArray ;


@property (nonatomic ,strong) UIButton * defineButton ;//确定
@property (nonatomic ,strong) UIButton * selectAll ;//全选
@property (nonatomic ,strong) UIButton * unselectAll ;//全不选

@end

@implementation DScreeningViewController

static NSString *const cellId = @"MXScreeningCollectionViewCell";
static NSString *const headerId = @"MXScreeningHeaderCollectionReusableView";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kColorWithRGBF(0xebf0f4) ;
    [self.view addSubview:self.collectionView];
    self.title = @"筛选" ;
    
    [self.view addSubview:self.selectAll] ;
    [self.view addSubview:self.unselectAll] ;
    [self.view addSubview:self.defineButton] ;
    
    mx_weakify(self) ;
    if (self.dataArray.count == 0) {
        self.refreshButton = [weakSelf addUpDataBtnWithTitle:@"" superView:weakSelf.collectionView] ;
    }
    self.updataBlock = ^{
        [weakSelf getNetworkData] ;
    } ;
}

- (UIButton *)selectAll {
    if (!_selectAll) {
        _selectAll = [UIButton buttonWithType:(UIButtonTypeCustom)] ;
        _selectAll.frame = CGRectMake(0, screen_height - scaleWithSize(54) - TABBAR_FRAME - STATUS_AND_NAVIGATION_HEIGHT, screen_width / 3, scaleWithSize(54)) ;
        _selectAll.backgroundColor = [UIColor whiteColor] ;
        [_selectAll setTitle:@"全选" forState:(UIControlStateNormal)] ;
        [_selectAll setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)] ;
        [_selectAll addTarget:self action:@selector(selectorSelectAllButton:) forControlEvents:(UIControlEventTouchDown)];
    }
    return _selectAll ;
}
- (UIButton *)unselectAll {
    if (!_unselectAll) {
        _unselectAll = [UIButton buttonWithType:(UIButtonTypeCustom)] ;
        _unselectAll.frame = CGRectMake(CGRectGetMaxX(self.selectAll.frame), screen_height - scaleWithSize(54) - TABBAR_FRAME - STATUS_AND_NAVIGATION_HEIGHT, screen_width / 3, scaleWithSize(54)) ;
        _unselectAll.backgroundColor = [UIColor whiteColor] ;
        [_unselectAll setTitle:@"全不选" forState:(UIControlStateNormal)] ;
        [_unselectAll setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)] ;
        [_unselectAll addTarget:self action:@selector(selectorUnSelectAllButton:) forControlEvents:(UIControlEventTouchDown)] ;
    }
    return _unselectAll ;
}

- (UIButton *)defineButton {
    
    if (!_defineButton) {
        _defineButton = [UIButton buttonWithType:(UIButtonTypeCustom)] ;
        _defineButton.frame = CGRectMake(CGRectGetMaxX(self.unselectAll.frame), screen_height - scaleWithSize(54) - TABBAR_FRAME - STATUS_AND_NAVIGATION_HEIGHT, screen_width / 3, scaleWithSize(54)) ;
        _defineButton.backgroundColor = mx_Wode_colorBlue2374e4 ;
        [_defineButton setTitle:@"确定" forState:(UIControlStateNormal)] ;
        [_defineButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)] ;
        [_defineButton addTarget:self action:@selector(selectorDefineButton:) forControlEvents:(UIControlEventTouchDown)] ;
    }
    return _defineButton ;
}

- (void)selectorSelectAllButton:(UIButton *)button {
    
//    if ([notification.userInfo[@"selectIndex"] isEqualToString:@"0"]) {
        
        self.allScreeningIDsString = @"" ;
        if (self.dataArray.count > 0) {
            for (int i = 0; i< self.dataArray.count; i ++) {
                MXDAllEventsModel * eventsModel = self.dataArray[i] ;
                for (int j = 0; j < [eventsModel.events count]; j ++) {
                    MXFilterModel * model = eventsModel.events[j] ;
                    model.isSelect = 0 ;
                    [eventsModel.events replaceObjectAtIndex:j withObject:model];
                    [self.dataArray replaceObjectAtIndex:i withObject:eventsModel];
                    //                    [self.dataArray[i] replaceObjectAtIndex:j withObject:model];
                    
                    if (model.ID) {
                        if ([self.allScreeningIDsString isEqualToString:@""]) {
                            self.allScreeningIDsString = [NSString stringWithFormat:@"%ld",(long)model.ID] ;
                        } else {
                            self.allScreeningIDsString = [NSString stringWithFormat:@"%@|%ld",self.allScreeningIDsString,(long)model.ID] ;
                        }
                    }
                    
                    
                }
            }
        }
        
        //        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        //        [defaults setValue:self.allScreeningIDsString forKey:@"AllScreeningKey1"] ;
        //        [defaults synchronize];
        [self setAllScreeningKey] ;
        
        [self.collectionView reloadData];
        
        //        [self.selectMutDic removeAllObjects] ;
//        [self delegateSelectNameMutDic];
//    }
    
}
- (void)selectorUnSelectAllButton:(UIButton *)button {
    
    if (self.dataArray.count > 0) {
        for (int i = 0; i< self.dataArray.count; i ++) {
            MXDAllEventsModel * eventsModel = self.dataArray[i] ;
            for (int j = 0; j < [eventsModel.events count]; j ++) {
                MXFilterModel * model = eventsModel.events[j] ;
                model.isSelect = 1 ;
                [eventsModel.events replaceObjectAtIndex:j withObject:model];
                [self.dataArray replaceObjectAtIndex:i withObject:eventsModel];
                //                    [self.dataArray[i] replaceObjectAtIndex:j withObject:model];
            }
        }
    }
    //        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    self.allScreeningIDsString = @"" ;
    //        [defaults setValue:@"" forKey:@"AllScreeningKey1"] ;
    //        [defaults synchronize];
    [self setAllScreeningKey] ;
    
    [self.collectionView reloadData];
    
}

- (void)selectorDefineButton:(UIButton *)button {
    
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults] ;
    if ([self.optType isEqualToString:@"1"]) {
        
        [defaults setValue:[defaults objectForKey:@"AllScreeningKeyEnd1"] forKey:@"AllScreeningKeyEnd"] ;
        [defaults setValue:[defaults objectForKey:@"AllAsianPlateKeyEnd1"] forKey:@"AllAsianPlateKeyEnd"] ;
    } else if ([self.optType isEqualToString:@"2"]) {
        
        [defaults setValue:[defaults objectForKey:@"AllScreeningKeyWorldCup1"] forKey:@"AllScreeningKeyWorldCup"] ;
        [defaults setValue:[defaults objectForKey:@"AllAsianPlateKeyWorldCup1"] forKey:@"AllAsianPlateKeyWorldCup"] ;
    } else if ([self.optType isEqualToString:@"3"]) {
        
        [defaults setValue:[defaults objectForKey:@"AllScreeningKeyImm1"] forKey:@"AllScreeningKeyCollect"] ;
        [defaults setValue:[defaults objectForKey:@"AllAsianPlateKeyImm1"] forKey:@"AllAsianPlateKeyCollect"] ;
    } else {
        
        [defaults setValue:[defaults objectForKey:@"AllScreeningKeyImm1"] forKey:@"AllScreeningKeyImm"] ;
        [defaults setValue:[defaults objectForKey:@"AllAsianPlateKeyImm1"] forKey:@"AllAsianPlateKeyImm"] ;
    }
    
    
    //创建通知
    NSNotification * notification =[NSNotification notificationWithName:@"selectDefineButton" object:nil userInfo:nil];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
    [self.navigationController popViewControllerAnimated:YES] ;
//    [self dismissViewControllerAnimated:YES completion:nil] ;
    
}

#pragma mark - network
- (void)getNetworkData {
    
    NSString *timeStr = [MXLJUtil getNowDateTimeString];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    MXSSToolConfig * userModel = [MXssWodeUtils loadPersonInfo] ;
    NSString *userId =[NSString stringWithFormat:@"%@",userModel.userId];
    if (userModel.userId) {
        [parameters setObject:userId forKey:@"userId"] ;
    }
    
    [parameters setObject:self.optType forKey:@"opid"];
    
    [parameters setObject:@"1" forKey:@"operationType"] ;
    [parameters setObject:timeStr forKey:@"time"];
    NSMutableDictionary *dic= [MXLJUtil sortedDictionary:parameters];
    NSString *url = [NSString stringWithFormat:@"%@%@", SERVER_HOST, MXApiCommonEventList2];
    
    [SVProgressHUD showWithStatus:@"正在加载..."];
    
    mx_weakify(self);
    [[WebManager sharedManager]requestWithMethod:POST WithUrl:url WithParams:dic WithSuccessBlock:^(NSDictionary *dic) {
        [weakSelf.collectionView.mj_header endRefreshing];
        if ([dic[@"code"] isEqualToString:@"0"]) {
            
            if ([dic[@"data"] count]) {
                
                weakSelf.dataArray = [MXDAllEventsModel mj_objectArrayWithKeyValuesArray:dic[@"data"]] ;
                for (int i = weakSelf.dataArray.count - 1; i>0; i --) {
                    if ([[weakSelf.dataArray[i] events] count] == 0) {
                        [weakSelf.dataArray removeObjectAtIndex:i];
                    }
                }
                
                [weakSelf arraySorting:weakSelf.dataArray];
                
                weakSelf.removeUpdataBlock() ;
                
            } else {
                [SVProgressHUD showErrorWithStatus:@"暂无数据"];
                if (weakSelf.dataArray.count == 0) {
                    [weakSelf.refreshButton setTitle:@"暂无数据" forState:(UIControlStateNormal)] ;
                    [weakSelf.view addSubview:weakSelf.refreshButton];
                }
            }
            
            [SVProgressHUD dismiss];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakSelf.collectionView.mj_header endRefreshing] ;
                
                [weakSelf.collectionView reloadData];
            });
            
            
        } else {
            [SVProgressHUD showErrorWithStatus:dic[@"msg"]];
            if (self.dataArray.count == 0) {
                [weakSelf.refreshButton setTitle:dic[@"msg"] forState:(UIControlStateNormal)] ;
                [weakSelf.view addSubview:weakSelf.refreshButton];
            }
            
        }
        
    } WithFailureBlock:^(NSError *error) {
        [weakSelf.collectionView.mj_header endRefreshing];
        if (weakSelf.dataArray.count == 0) {
            [weakSelf.refreshButton setTitle:@"网络错误" forState:(UIControlStateNormal)] ;
            [weakSelf.view addSubview:weakSelf.refreshButton];
        }
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }] ;
}
#pragma mark -  存 所有的ID
- (NSMutableArray *)arraySorting:(NSMutableArray *) mutableArray {
    
    self.allScreeningIDsString = @"" ;
    for (MXDAllEventsModel * model in mutableArray) {
        for (MXFilterModel * filterModel in model.events) {
            //存 所有的ID
            if (filterModel.ID) {
                if (![self.allScreeningIDsString isEqualToString:@""]) {
                    self.allScreeningIDsString = [NSString stringWithFormat:@"%@|%ld",self.allScreeningIDsString,(long)filterModel.ID] ;
                } else {
                    self.allScreeningIDsString = [NSString stringWithFormat:@"%ld",(long)filterModel.ID] ;
                }
            }
        }
        
    }
    
    
    [self setAllScreeningKey] ;
    
    return mutableArray ;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated] ;
    if (!self.dataArray.count) {
        [self getNetworkData] ;
    }
    [self setAllScreeningKey] ;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array] ;
    }
    return _dataArray ;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _customLayout = [[UICollectionViewFlowLayout alloc]init] ;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, screen_width, screen_height - scaleWithSize(54) - TABBAR_FRAME - STATUS_AND_NAVIGATION_HEIGHT) collectionViewLayout:_customLayout] ;
        _collectionView.backgroundColor = [UIColor clearColor] ;
        _collectionView.delegate = self ;
        _collectionView.dataSource = self ;
        
        [_collectionView registerClass:[MXScreeningCollectionViewCell class] forCellWithReuseIdentifier:cellId] ;
        
        [_collectionView registerClass:[MXScreeningHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId] ;
        
//        __weak typeof(self) weakSelf = self ;
        
    }
    return _collectionView ;
}


#pragma mark - UICollectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataArray.count ;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.dataArray.count > 0) {
        MXDAllEventsModel * model = self.dataArray[section] ;
        return [model.events count] ;
    }
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MXScreeningCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath] ;
    
    cell.layer.cornerRadius = 5 ;
    cell.layer.masksToBounds = YES ;
    cell.backgroundColor = mx_Wode_colorBlue2374e4 ;
    cell.nameLabel.textColor = [UIColor whiteColor] ;
    cell.numberLabel.textColor = [UIColor whiteColor] ;
    
    if (self.dataArray.count > 0) {
        MXDAllEventsModel * model = self.dataArray[indexPath.section] ;
        //
        if (model.events.count) {
            MXFilterModel * eventsModel = model.events[indexPath.row] ;
            cell.model = eventsModel;
            
            if (eventsModel.isSelect == 1) {
                cell.backgroundColor = [UIColor whiteColor] ;
                cell.nameLabel.textColor = [UIColor darkGrayColor] ;
                cell.numberLabel.textColor = [UIColor darkGrayColor] ;
            }
        }
        
    }
    return cell ;
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//
//    if (self.dataArray.count > 0) {
//        MXDAllEventsModel * model = self.dataArray[section] ;
//        if ([model.events count] == 0) {
//            return (CGSize){screen_width,scaleWithSize(0)};
//        }
//    }
//
//    return (CGSize){screen_width,scaleWithSize(0.01)};
//}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//
//        MXScreeningHeaderCollectionReusableView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath] ;
//
//        MXDAllEventsModel * model = self.dataArray[indexPath.section] ;
//
//        headerView.label.text = model.letter;
//
//        return headerView ;
//    }
//
//    return nil ;
//}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(scaleWithSize(108), scaleWithSize(32)) ;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(scaleWithSize(15), scaleWithSize(15), 0, scaleWithSize(15)) ;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return scaleWithSize(7) ;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return scaleWithSize(7) ;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.dataArray.count > 0) {
        
        MXDAllEventsModel * eventsModel = self.dataArray[indexPath.section] ;
        MXFilterModel * model = eventsModel.events[indexPath.row] ;
        
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        if ([self.optType isEqualToString:@"1"]) {
            self.allScreeningIDsString = [defaults valueForKey:@"AllScreeningKeyEnd1"] ;
        } else if ([self.optType isEqualToString:@"2"]) {
            self.allScreeningIDsString = [defaults valueForKey:@"AllScreeningKeyWorldCup1"] ;
        } else{
            self.allScreeningIDsString = [defaults valueForKey:@"AllScreeningKeyImm1"] ;
        }
        
        if (model.isSelect == 1) {
            model.isSelect = 0;
            if ([self.allScreeningIDsString isEqualToString:@""]) {
                self.allScreeningIDsString = [NSString stringWithFormat:@"%ld",(long)model.ID] ;
            } else {
                self.allScreeningIDsString = [NSString stringWithFormat:@"%@|%ld",self.allScreeningIDsString,(long)model.ID] ;
            }
            
        } else {
            NSMutableArray * array =[NSMutableArray arrayWithArray:[self.allScreeningIDsString componentsSeparatedByString:@"|"]]  ;
            [array removeObject:[NSString stringWithFormat:@"%ld",model.ID]];
            self.allScreeningIDsString = @"" ;
            for (NSString * string in array) {
                if (string.length) {
                    if ([self.allScreeningIDsString isEqualToString:@""]) {
                        self.allScreeningIDsString = string ;
                    } else {
                        self.allScreeningIDsString = [NSString stringWithFormat:@"%@|%@",self.allScreeningIDsString,string] ;
                    }
                }
            }
            
            model.isSelect = 1;
        }
        
//        NSLog(@"%@",self.allScreeningIDsString) ;
        
        [self setAllScreeningKey] ;
        
        [eventsModel.events replaceObjectAtIndex:indexPath.row withObject:model];
        
        [self.dataArray replaceObjectAtIndex:indexPath.section withObject:eventsModel];
    }
    
    [self.collectionView reloadData] ;
}
- (void)setAllScreeningKey {
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    if ([self.optType isEqualToString:@"1"]) {
        [defaults setValue:self.allScreeningIDsString forKey:@"AllScreeningKeyEnd1"] ;
    } else if ([self.optType isEqualToString:@"2"]) {
        [defaults setValue:self.allScreeningIDsString forKey:@"AllScreeningKeyWorldCup1"] ;
    } else {
        [defaults setValue:self.allScreeningIDsString forKey:@"AllScreeningKeyImm1"] ;
    }
    
    [defaults synchronize];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
